package net.didactylos.helpline.action;

import org.hibernate.Session;

import net.didactylos.helpline.data.User;
import net.didactylos.helpline.stripes.bean.HelplineActionBean;
import net.didactylos.helpline.stripes.security.Capabilities;
import net.didactylos.helpline.stripes.security.Secured;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.validation.*;

public class ChangePasswordAction extends HelplineActionBean
{
	@Validate(required=true, minlength=8)
	private String newPassword;
	
	@Validate(required=true)
	private String confirmPassword;

	public String getNewPassword()
	{
		return newPassword;
	}

	public void setNewPassword(String newPassword)
	{
		this.newPassword = newPassword;
	}

	public String getConfirmPassword()
	{
		return confirmPassword;
	}

	public void setConfirmPassword(String confirmPassword)
	{
		this.confirmPassword = confirmPassword;
	}

	@DontValidate
	@DefaultHandler
	@Secured(Capabilities.SIGN_IN)
	public Resolution view()
	{
		return new ForwardResolution("changePassword.jspx");
	}
	
	@Secured(Capabilities.SIGN_IN)
	public Resolution changePassword()
	{
		if (!newPassword.equals(confirmPassword))
		{
			ValidationError error = new LocalizableError("passwordsUnequal");
            getContext().getValidationErrors().add("confirmPassword", error);
            return getContext().getSourcePageResolution();
		}
		Session session = getContext().getSession();
		
		User user = getContext().getUser();
		user.setPassword(newPassword);
		session.update(user);
        
        getContext().getMessages().add(new LocalizableMessage("changePasswordMessage"));

		return new RedirectResolution(ChangePasswordAction.class);
	}
}
